extends Control
class_name Battle5v5Scene

## 5v5回合制战斗场景
## 实现玩家+4个幻兽 vs 5个怪物的战斗系统

signal battle_ended(victory: bool, final_player_hp: int, defeated_enemies_data: Array[Dictionary])

# 默认图标路径
const DEFAULT_PLAYER_ICON = "res://assets/icons/player_icon.svg"
const DEFAULT_PHANTOM_BEAST_ICON = "res://assets/icons/phantom_beast_icon.svg"
const DEFAULT_MONSTER_ICON = "res://assets/icons/monster_icon.svg"

# UI节点引用
@onready var player_team_container: VBoxContainer = $PlayerTeam/TeamContainer
@onready var enemy_team_container: VBoxContainer = $EnemyTeam/TeamContainer
@onready var battle_log: RichTextLabel = $BattleLog
@onready var turn_timer: Timer = $TurnTimer
@onready var current_speed_label: Label = $TopUI/CurrentSpeedLabel
@onready var turn_label: Label = $TopUI/TurnLabel
@onready var exit_button: Button = $ExitButton
@onready var speed_1x_button: Button = $TopUI/SpeedControlPanel/Speed1xButton
@onready var speed_2x_button: Button = $TopUI/SpeedControlPanel/Speed2xButton
@onready var speed_5x_button: Button = $TopUI/SpeedControlPanel/Speed5xButton
@onready var speed_10x_button: Button = $TopUI/SpeedControlPanel/Speed10xButton
@onready var speed_20x_button: Button = $TopUI/SpeedControlPanel/Speed20xButton

# 战斗数据
var player_team: Array[Dictionary] = []  # 玩家队伍数据（玩家+幻兽）
var enemy_team: Array[Dictionary] = []   # 敌方队伍数据
var all_combatants: Array[Dictionary] = []  # 所有战斗单位
var action_queue: Array[Dictionary] = []  # 行动队列
var current_action_index: int = 0
var battle_active: bool = true
var base_turn_delay: float = 1.5  # 基础行动间隔时间
var current_speed_multiplier: float = 1.0  # 当前速度倍数
var turn_delay: float = 1.5  # 实际行动间隔时间

# 预先计算的掉落物品
var predetermined_drops: Array[Dictionary] = []

# UI组件数组
var player_team_ui: Array[Dictionary] = []
var enemy_team_ui: Array[Dictionary] = []

func _ready():
	"""初始化战斗场景"""
	# 不在这里调用setup_battle_ui，等待数据设置完成后调用
	exit_button.pressed.connect(_on_exit_button_pressed)
	
	# 监听窗口大小变化
	get_viewport().size_changed.connect(_on_viewport_size_changed)
	
	# 连接速度控制按钮
	speed_1x_button.pressed.connect(_on_speed_1x_pressed)
	speed_2x_button.pressed.connect(_on_speed_2x_pressed)
	speed_5x_button.pressed.connect(_on_speed_5x_pressed)
	speed_10x_button.pressed.connect(_on_speed_10x_pressed)
	speed_20x_button.pressed.connect(_on_speed_20x_pressed)
	
	# 从PlayerManager获取保存的速度设置
	if PlayerManager:
		current_speed_multiplier = PlayerManager.get_battle_speed_multiplier()
		update_speed_buttons()
		update_turn_delay()
		update_current_speed_display()

	# 等待数据设置完成后开始战斗
	await get_tree().process_frame
	start_battle()

func setup_battle_ui():
	"""设置战斗界面"""
	print("开始设置战斗UI...")
	
	# 清空容器
	for child in player_team_container.get_children():
		child.queue_free()
	for child in enemy_team_container.get_children():
		child.queue_free()
	
	player_team_ui.clear()
	enemy_team_ui.clear()
	
	# 等待一帧确保子节点被清理
	await get_tree().process_frame
	
	# 创建玩家队伍UI
	print("创建玩家队伍UI，队伍大小: ", player_team.size())
	for i in range(player_team.size()):
		var unit_data = player_team[i]
		var unit_ui = create_unit_ui(unit_data, true)
		player_team_container.add_child(unit_ui.container)
		player_team_ui.append(unit_ui)
		print("已创建玩家队伍UI: ", unit_ui.container.name)
	
	# 创建敌方队伍UI
	print("创建敌方队伍UI，队伍大小: ", enemy_team.size())
	for i in range(enemy_team.size()):
		var unit_data = enemy_team[i]
		var unit_ui = create_unit_ui(unit_data, false)
		enemy_team_container.add_child(unit_ui.container)
		enemy_team_ui.append(unit_ui)
		print("已创建敌方队伍UI: ", unit_ui.container.name)
	
	# 清空战斗日志
	battle_log.clear()
	add_battle_log("5v5战斗开始！")
	add_battle_log("玩家队伍 vs 敌方队伍")
	
	# 调整UI尺寸以适应当前屏幕大小
	_adjust_ui_for_screen_size()
	
	print("战斗UI设置完成")

func _on_viewport_size_changed():
	"""窗口大小变化时调整UI"""
	_adjust_ui_for_screen_size()

func _adjust_ui_for_screen_size():
	"""根据屏幕大小调整UI组件尺寸"""
	var viewport_size = get_viewport().size
	var scale_factor = min(viewport_size.x / 1920.0, viewport_size.y / 1080.0)
	scale_factor = max(scale_factor, 0.3)  # 最小缩放比例
	
	# 调整现有的UI组件
	for ui_data in player_team_ui:
		if ui_data.has("container"):
			_adjust_unit_ui_size(ui_data, scale_factor)
	
	for ui_data in enemy_team_ui:
		if ui_data.has("container"):
			_adjust_unit_ui_size(ui_data, scale_factor)

func _adjust_unit_ui_size(ui_data: Dictionary, scale_factor: float):
	"""调整单个单位UI的尺寸"""
	var base_container_size = Vector2(80, 110)
	var base_sprite_size = Vector2(50, 50)
	var base_hp_bar_size = Vector2(50, 15)
	
	ui_data.container.custom_minimum_size = base_container_size * scale_factor
	ui_data.sprite.custom_minimum_size = base_sprite_size * scale_factor
	ui_data.hp_bar.custom_minimum_size = base_hp_bar_size * scale_factor

func create_unit_ui(unit_data: Dictionary, is_player_team: bool) -> Dictionary:
	"""创建单位UI组件"""
	var container = VBoxContainer.new()
	# 初始尺寸，会在_adjust_ui_for_screen_size中动态调整
	container.custom_minimum_size = Vector2(80, 110)
	# 确保battle_id存在并设置容器名称
	var battle_id = unit_data.get("battle_id", "unknown")
	container.name = battle_id
	print("创建UI容器: ", battle_id, " 队伍: ", "player" if is_player_team else "enemy")
	
	# 精灵图像
	var sprite = TextureRect.new()
	sprite.custom_minimum_size = Vector2(80, 80)
	sprite.expand_mode = TextureRect.EXPAND_FIT_WIDTH_PROPORTIONAL
	sprite.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
	
	# 加载精灵纹理
	var sprite_path = unit_data.get("sprite_path", "")
	if sprite_path != "" and ResourceLoader.exists(sprite_path):
		var texture = load(sprite_path)
		if texture != null:
			sprite.texture = texture
	else:
		# 使用默认图标
		var default_icon_path = ""
		if unit_data.get("is_player", false):
			default_icon_path = DEFAULT_PLAYER_ICON
		elif unit_data.get("is_phantom_beast", false):
			default_icon_path = DEFAULT_PHANTOM_BEAST_ICON
		else:
			default_icon_path = DEFAULT_MONSTER_ICON
		
		if ResourceLoader.exists(default_icon_path):
			sprite.texture = load(default_icon_path)
		else:
			print("警告：无法加载默认图标: ", default_icon_path)
	
	# 名称标签
	var name_label = Label.new()
	name_label.text = unit_data.get("name", "未知")
	name_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	name_label.add_theme_font_size_override("font_size", 14)
	
	# 血量条
	var hp_bar = ProgressBar.new()
	hp_bar.custom_minimum_size = Vector2(50, 12)
	hp_bar.max_value = unit_data.get("max_hp", 100)
	hp_bar.value = unit_data.get("current_hp", 100)
	hp_bar.show_percentage = false
	
	# 设置血量条颜色
	var style_box = StyleBoxFlat.new()
	if is_player_team:
		style_box.bg_color = Color.GREEN
	else:
		style_box.bg_color = Color.RED
	hp_bar.add_theme_stylebox_override("fill", style_box)
	
	# 血量标签
	var hp_label = Label.new()
	hp_label.text = "HP: %d/%d" % [unit_data.get("current_hp", 100), unit_data.get("max_hp", 100)]
	hp_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	hp_label.add_theme_font_size_override("font_size", 12)
	
	# 等级标签（如果有）
	var level_label = Label.new()
	if unit_data.has("level"):
		level_label.text = "Lv.%d" % unit_data.level
	else:
		level_label.text = ""
	level_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	
	# 组装UI
	container.add_child(sprite)
	container.add_child(name_label)
	container.add_child(level_label)
	container.add_child(hp_bar)
	container.add_child(hp_label)
	
	return {
		"container": container,
		"sprite": sprite,
		"name_label": name_label,
		"level_label": level_label,
		"hp_bar": hp_bar,
		"hp_label": hp_label
	}

func start_battle():
	"""开始战斗"""
	battle_active = true
	
	# 合并所有战斗单位
	all_combatants.clear()
	for i in range(player_team.size()):
		var unit = player_team[i]
		unit["team"] = "player"
		# 不要重新设置battle_id，保持与UI容器名称一致
		print("添加玩家队伍单位: ", unit.get("battle_id"), " 名称: ", unit.get("name"))
		all_combatants.append(unit)
	for i in range(enemy_team.size()):
		var unit = enemy_team[i]
		unit["team"] = "enemy"
		# 不要重新设置battle_id，保持与UI容器名称一致
		print("添加敌方队伍单位: ", unit.get("battle_id"), " 名称: ", unit.get("name"))
		all_combatants.append(unit)
	
	# 计算行动队列
	calculate_action_queue()
	current_action_index = 0
	
	# 更新回合显示
	update_turn_display()
	
	# 设置行动计时器
	turn_timer.wait_time = turn_delay
	turn_timer.timeout.connect(_on_action_timeout)
	turn_timer.start()

func calculate_action_queue():
	"""计算行动队列，基于攻击速度"""
	action_queue.clear()
	
	# 为每个存活的战斗单位创建行动数据
	var actions_with_speed = []
	for i in range(all_combatants.size()):
		var unit = all_combatants[i]
		if unit.get("current_hp", 0) > 0:  # 只有存活的单位才能行动
			actions_with_speed.append({
				"unit_index": i,
				"speed": unit.get("attack_speed", 100),
				"team": unit.get("team", "")
			})
	
	# 按速度排序（速度高的先行动）
	actions_with_speed.sort_custom(func(a, b): return a.speed > b.speed)
	
	# 创建行动队列
	for action_data in actions_with_speed:
		action_queue.append(action_data)
	
	print("行动队列计算完成，共 %d 个行动" % action_queue.size())

func _on_action_timeout():
	"""行动超时处理"""
	if not battle_active or action_queue.is_empty():
		return
	
	# 执行当前行动
	var current_action = action_queue[current_action_index]
	var unit_index = current_action.unit_index
	
	# 检查单位是否还存活
	if unit_index < all_combatants.size() and all_combatants[unit_index].get("current_hp", 0) > 0:
		execute_unit_action(unit_index)
	
	# 检查战斗是否结束
	if check_battle_end():
		return
	
	# 移动到下一个行动
	current_action_index += 1
	if current_action_index >= action_queue.size():
		# 重新计算行动队列（移除死亡单位）
		calculate_action_queue()
		current_action_index = 0
	
	# 更新回合显示
	update_turn_display()
	
	# 重新启动计时器
	turn_timer.start()

func execute_unit_action(unit_index: int):
	"""执行单位行动"""
	var attacker = all_combatants[unit_index]
	var attacker_team = attacker.get("team", "")
	
	# 选择目标
	var target_index = select_target(attacker_team)
	if target_index == -1:
		return  # 没有有效目标
	
	var target = all_combatants[target_index]
	
	# 计算伤害
	var damage = calculate_damage(attacker.get("attack", 10), target.get("defense", 5))
	target["current_hp"] = max(0, target.get("current_hp", 100) - damage)
	
	# 更新UI
	update_unit_ui(target_index)
	
	# 添加战斗日志
	var target_team = target.get("team", "")
	add_battle_log_with_colors("%s 攻击了 %s，造成 %d 点伤害！" % [attacker.get("name", "未知"), target.get("name", "未知"), damage], 
		attacker.get("name", "未知"), target.get("name", "未知"), attacker_team, target_team)
	
	# 播放攻击动画
	play_attack_animation(unit_index, target_index)
	
	# 检查目标是否死亡
	if target.get("current_hp", 0) <= 0:
		add_battle_log_with_colors("%s 被击败了！" % target.get("name", "未知"), 
			"", target.get("name", "未知"), "", target_team)

func select_target(attacker_team: String) -> int:
	"""选择攻击目标"""
	var possible_targets = []
	
	# 找到敌对队伍的存活单位
	for i in range(all_combatants.size()):
		var unit = all_combatants[i]
		if unit.get("team", "") != attacker_team and unit.get("current_hp", 0) > 0:
			possible_targets.append(i)
	
	if possible_targets.is_empty():
		return -1
	
	# 随机选择一个目标
	return possible_targets[randi() % possible_targets.size()]

func calculate_damage(attack: int, defense: int) -> int:
	"""计算伤害"""
	var base_damage = attack - defense
	var random_factor = randf_range(0.8, 1.2)  # 80%-120%的随机伤害
	return max(1, int(base_damage * random_factor))  # 至少造成1点伤害

func update_unit_ui(unit_index: int):
	"""更新单位UI"""
	var unit = all_combatants[unit_index]
	var battle_id = unit.get("battle_id", "")
	if battle_id == "":
		print("警告：单位没有battle_id")
		return
	
	# 查找对应的UI容器
	var unit_container: Control = null
	var is_player_team = unit.get("team", "") == "player"
	
	if is_player_team:
		unit_container = player_team_container.get_node_or_null(battle_id)
		if unit_container == null:
			print("警告：在玩家队伍容器中找不到单位UI容器: ", battle_id)
			print("玩家队伍容器子节点: ")
			for child in player_team_container.get_children():
				print("  - ", child.name)
	else:
		unit_container = enemy_team_container.get_node_or_null(battle_id)
		if unit_container == null:
			print("警告：在敌方队伍容器中找不到单位UI容器: ", battle_id)
			print("敌方队伍容器子节点: ")
			for child in enemy_team_container.get_children():
				print("  - ", child.name)
	
	if unit_container == null:
		return
	
	# 更新血量条和血量文本
	if unit_container.get_child_count() >= 5:
		var hp_bar = unit_container.get_child(3) as ProgressBar
		var hp_label = unit_container.get_child(4) as Label
		
		if hp_bar != null:
			hp_bar.value = unit.get("current_hp", 0)
		
		if hp_label != null:
			hp_label.text = "HP: %d/%d" % [unit.get("current_hp", 0), unit.get("max_hp", 100)]
	
	# 如果单位死亡，添加视觉效果
	if unit.get("current_hp", 0) <= 0:
		unit_container.modulate = Color(0.5, 0.5, 0.5, 0.7)  # 变暗表示死亡
	else:
		unit_container.modulate = Color.WHITE  # 恢复正常颜色

func play_attack_animation(attacker_index: int, target_index: int):
	"""播放攻击动画"""
	# 简单的攻击动画效果
	var attacker = all_combatants[attacker_index]
	var attacker_ui: Dictionary
	
	# 获取攻击者UI
	if attacker.get("team", "") == "player":
		for i in range(player_team.size()):
			if player_team[i] == attacker and i < player_team_ui.size():
				attacker_ui = player_team_ui[i]
				break
	else:
		for i in range(enemy_team.size()):
			if enemy_team[i] == attacker and i < enemy_team_ui.size():
				attacker_ui = enemy_team_ui[i]
				break
	
	if not attacker_ui.is_empty():
		var tween = create_tween()
		var original_position = attacker_ui.container.position
		
		# 前冲动画
		tween.tween_property(attacker_ui.container, "position:x", original_position.x + 20, 0.2)
		tween.tween_property(attacker_ui.container, "position:x", original_position.x, 0.2)

func update_turn_display():
	"""更新回合显示"""
	if action_queue.is_empty() or current_action_index >= action_queue.size():
		turn_label.text = "计算下一轮行动..."
		return
	
	var current_action = action_queue[current_action_index]
	var unit_index = current_action.unit_index
	
	if unit_index < all_combatants.size():
		var current_unit = all_combatants[unit_index]
		turn_label.text = "当前行动: %s" % current_unit.get("name", "未知")

func check_battle_end() -> bool:
	"""检查战斗是否结束"""
	# 检查玩家队伍是否全部死亡
	var player_alive = false
	for unit in player_team:
		if unit.get("current_hp", 0) > 0:
			player_alive = true
			break
	
	# 检查敌方队伍是否全部死亡
	var enemy_alive = false
	for unit in enemy_team:
		if unit.get("current_hp", 0) > 0:
			enemy_alive = true
			break
	
	if not player_alive:
		end_battle(false)  # 玩家失败
		return true
	elif not enemy_alive:
		end_battle(true)   # 玩家胜利
		return true
	
	return false

func end_battle(victory: bool):
	"""结束战斗"""
	print("[DEBUG] battle_5v5_scene end_battle 被调用，victory: ", victory)
	battle_active = false
	turn_timer.stop()
	
	if victory:
		add_battle_log("\n=== 胜利！ ===")
		add_battle_log("敌方队伍被全部击败！")
		
		# 简化奖励显示为四句话
		var reward_summary = get_battle_reward_summary(predetermined_drops)
		
		# 显示物品奖励
		if not reward_summary.items.is_empty():
			add_battle_log("获得物品: %s" % reward_summary.items)
		
		# 显示幻兽奖励
		if not reward_summary.phantom_beasts.is_empty():
			add_battle_log("获得幻兽: %s" % reward_summary.phantom_beasts)
		
		# 显示经验奖励
		var total_exp = 0
		for enemy in enemy_team:
			total_exp += enemy.get("exp_reward", 0)
		if total_exp > 0:
			add_battle_log("获得经验: 玩家和幻兽各获得%d点" % total_exp)
		
		# 显示金币奖励
		if reward_summary.gold > 0:
			add_battle_log("获得金币: %d" % reward_summary.gold)
	else:
		add_battle_log("\n=== 失败... ===")
		add_battle_log("玩家队伍被击败了...")
		add_battle_log("1秒后自动返回场景...")
	
	# 延迟发送信号，让玩家看到结果
	var delay_time = 3.0 if victory else 1.0
	await get_tree().create_timer(delay_time).timeout
	
	# 获取玩家最终血量（只有玩家，不包括幻兽）
	var final_player_hp = 0
	if not player_team.is_empty():
		final_player_hp = player_team[0].get("current_hp", 0)
	
	# 处理幻兽战斗后的状态变化
	if PhantomBeastManager != null and player_team.size() > 1:
		for i in range(1, player_team.size()):  # 跳过玩家（索引0），从幻兽开始
			var beast_battle_data = player_team[i]
			var battle_id = beast_battle_data.get("battle_id", "")
			
			# 从battle_id中提取幻兽ID（格式："phantom_0", "phantom_1"等）
			if battle_id.begins_with("phantom_"):
				var phantom_index = battle_id.substr(8).to_int()  # 提取数字部分
				var active_formation = PhantomBeastManager.get_active_formation_ids()
				
				if phantom_index < active_formation.size():
					var beast_id = active_formation[phantom_index]
					var current_hp = beast_battle_data.get("current_hp", 0)
					
					if victory:
						# 胜利时：如果幻兽死亡（血量<=0），则复活并设为1血
						if current_hp <= 0:
							PhantomBeastManager.set_phantom_beast_hp(beast_id, 1)
							add_battle_log("[color=yellow]%s 在胜利的荣光中重获新生！[/color]" % PhantomBeastManager.get_phantom_beast_display_name(beast_id))
							print("幻兽复活: %s -> 1血" % [beast_id])
						else:
							# 如果没死，正常保存血量
							PhantomBeastManager.set_phantom_beast_hp(beast_id, current_hp)
							print("保存幻兽血量: %s -> %d" % [beast_id, current_hp])
					else:
						# 失败时：所有上阵幻兽都死亡
						PhantomBeastManager.set_phantom_beast_hp(beast_id, 0)
						print("战败，幻兽死亡: %s" % beast_id)
	
	print("[DEBUG] battle_5v5_scene 发送 battle_ended 信号，victory: ", victory)
	var defeated_enemies: Array[Dictionary] = []
	if victory:
		# 确保类型安全的复制
		for enemy in enemy_team:
			defeated_enemies.append(enemy)
	battle_ended.emit(victory, final_player_hp, defeated_enemies)

func add_battle_log(text: String):
	"""添加战斗日志"""
	battle_log.append_text(text + "\n")
	# 自动滚动到底部
	battle_log.scroll_to_line(battle_log.get_line_count() - 1)

func add_battle_log_with_colors(text: String, attacker_name: String = "", target_name: String = "", attacker_team: String = "", target_team: String = ""):
	"""添加带颜色的战斗日志"""
	var colored_text = text
	
	# 为攻击者名称添加颜色
	if attacker_name != "":
		var attacker_color = "[color=green]" if attacker_team == "player" else "[color=plum]"
		colored_text = colored_text.replace(attacker_name, attacker_color + attacker_name + "[/color]")
	
	# 为目标名称添加颜色
	if target_name != "" and target_name != attacker_name:
		var target_color = "[color=green]" if target_team == "player" else "[color=plum]"
		colored_text = colored_text.replace(target_name, target_color + target_name + "[/color]")
	
	battle_log.append_text(colored_text + "\n")
	# 自动滚动到底部
	battle_log.scroll_to_line(battle_log.get_line_count() - 1)

func get_item_name(item_type: String, item_id: String) -> String:
	"""获取物品名称"""
	match item_type:
		"gold":
			return "金币"
		"equipment":
			if ItemManager != null:
				var equipment_data = ItemManager.get_equipment_by_id(item_id)
				if equipment_data != null:
					return equipment_data.name
			return item_id
		"consumable":
			if ItemManager != null:
				var consumable_data = ItemManager.get_consumable_by_id(item_id)
				if consumable_data != null:
					return consumable_data.name
			return item_id
		"material":
			if ItemManager != null:
				var material_data = ItemManager.get_material_by_id(item_id)
				if material_data != null:
					return material_data.name
			return item_id
		"phantom_beast":
			# 幻兽幼崽掉落
			if PhantomBeastManager:
				var beast_config = PhantomBeastManager.get_phantom_beast_config(item_id)
				if beast_config != null:
					return beast_config.name
			return item_id + "幼崽"
		_:
			return item_id

func get_battle_reward_summary(drops: Array[Dictionary]) -> Dictionary:
	"""获取战斗奖励汇总"""
	var summary = {
		"items": "",
		"phantom_beasts": "",
		"gold": 0
	}
	
	var item_list: Array[String] = []
	var beast_list: Array[String] = []
	
	# 分类处理掉落物品
	for drop in drops:
		var item_name = get_item_name(drop["type"], drop["id"])
		var quantity = drop["quantity"]
		
		if drop["type"] == "gold":
			summary.gold += quantity
		elif drop["type"] == "phantom_beast":
			if quantity > 1:
				beast_list.append("%s x%d" % [item_name, quantity])
			else:
				beast_list.append(item_name)
		else:
			if quantity > 1:
				item_list.append("%s x%d" % [item_name, quantity])
			else:
				item_list.append(item_name)
	
	# 合并为字符串
	if not item_list.is_empty():
		summary.items = ", ".join(item_list)
	if not beast_list.is_empty():
		summary.phantom_beasts = ", ".join(beast_list)
	
	return summary

func display_drops_with_merged_gold(drops: Array[Dictionary]):
	"""显示掉落物品，将金币合并显示在最后"""
	var total_gold = 0
	var other_drops: Array[Dictionary] = []
	
	# 分离金币和其他物品
	for drop in drops:
		if drop["type"] == "gold":
			total_gold += drop["quantity"]
		else:
			other_drops.append(drop)
	
	# 先显示其他物品
	for drop in other_drops:
		var item_name = get_item_name(drop["type"], drop["id"])
		var quantity = drop["quantity"]
		
		if quantity > 1:
			add_battle_log("获得: %s x%d" % [item_name, quantity])
		else:
			add_battle_log("获得: %s" % item_name)
	
	# 最后显示合并的金币
	if total_gold > 0:
		add_battle_log("获得: 金币 x%d" % total_gold)

func set_player_team_data(team_data: Array[Dictionary]):
	"""设置玩家队伍数据（玩家+幻兽）"""
	player_team = team_data.duplicate(true)
	# 不在这里调用setup_battle_ui，等待所有数据设置完成后统一调用

func set_enemy_team_data(team_data: Array[Dictionary]):
	"""设置敌方队伍数据"""
	enemy_team = team_data.duplicate(true)
	# 数据设置完成后，如果节点已准备好且两个队伍数据都已设置则设置UI
	if is_node_ready() and not player_team.is_empty() and not enemy_team.is_empty():
		# 确保UI只被设置一次
		setup_battle_ui()

func set_predetermined_drops(drops: Array[Dictionary]):
	"""设置预先计算的掉落物品"""
	predetermined_drops = drops.duplicate()

func _on_exit_button_pressed():
	"""逃跑按钮处理"""
	if not battle_active:
		return
	
	# 逃跑成功率
	var escape_chance = 0.8
	if randf() < escape_chance:
		add_battle_log("成功逃跑了！")
		end_battle(false)  # 逃跑算作失败，但不会有惩罚
	else:
		add_battle_log("逃跑失败！")
		# 逃跑失败，敌方获得一次攻击机会
		for i in range(enemy_team.size()):
			if enemy_team[i].get("current_hp", 0) > 0:
				execute_unit_action(player_team.size() + i)
				break
		if check_battle_end():
			return
		# 重新启动计时器
		turn_timer.start()

# 速度控制按钮处理
func _on_speed_1x_pressed():
	"""1倍速按钮处理"""
	set_battle_speed(1.0)

func _on_speed_2x_pressed():
	"""2倍速按钮处理"""
	set_battle_speed(2.0)

func _on_speed_5x_pressed():
	"""5倍速按钮处理"""
	set_battle_speed(5.0)

func _on_speed_10x_pressed():
	"""10倍速按钮处理"""
	set_battle_speed(10.0)

func _on_speed_20x_pressed():
	"""20倍速按钮处理"""
	set_battle_speed(20.0)

func set_battle_speed(multiplier: float):
	"""设置战斗速度"""
	current_speed_multiplier = multiplier
	update_turn_delay()
	update_speed_buttons()
	
	# 保存到PlayerManager
	if PlayerManager:
		PlayerManager.set_battle_speed_multiplier(multiplier)
	
	# 如果计时器正在运行，重新设置等待时间
	if turn_timer.time_left > 0:
		var remaining_ratio = turn_timer.time_left / turn_timer.wait_time
		turn_timer.wait_time = turn_delay
		turn_timer.start(turn_delay * remaining_ratio)
	
	add_battle_log("战斗速度设置为: %sx" % multiplier)
	update_current_speed_display()

func update_turn_delay():
	"""更新行动间隔时间"""
	turn_delay = base_turn_delay / current_speed_multiplier
	turn_timer.wait_time = turn_delay

func update_speed_buttons():
	"""更新速度按钮状态"""
	speed_1x_button.button_pressed = (current_speed_multiplier == 1.0)
	speed_2x_button.button_pressed = (current_speed_multiplier == 2.0)
	speed_5x_button.button_pressed = (current_speed_multiplier == 5.0)
	speed_10x_button.button_pressed = (current_speed_multiplier == 10.0)
	speed_20x_button.button_pressed = (current_speed_multiplier == 20.0)

func update_current_speed_display():
	"""更新当前速度显示"""
	if current_speed_label:
		current_speed_label.text = "当前战斗速度: %sx" % current_speed_multiplier
